{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-11T06:51:55.873968Z",
     "start_time": "2019-02-11T06:51:46.360373Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/anaconda3/envs/Python3/lib/python3.6/site-packages/rasa_nlu/extractors/entity_synonyms.py:116: UserWarning: Found conflicting synonym definitions for 'aapl'. Overwriting target 'AAPL' with 'TSLA'. Check your training data and remove conflicting synonym definitions to prevent this from happening.\n",
      "  repr(replacement)))\n",
      "/anaconda3/envs/Python3/lib/python3.6/site-packages/rasa_nlu/extractors/entity_synonyms.py:116: UserWarning: Found conflicting synonym definitions for ''. Overwriting target 'TSLA' with 'AAPL'. Check your training data and remove conflicting synonym definitions to prevent this from happening.\n",
      "  repr(replacement)))\n",
      "[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.\n",
      "/anaconda3/envs/Python3/lib/python3.6/site-packages/sklearn/metrics/classification.py:1143: UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples.\n",
      "  'precision', 'predicted', average, warn_for)\n",
      "/anaconda3/envs/Python3/lib/python3.6/site-packages/sklearn/metrics/classification.py:1143: UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples.\n",
      "  'precision', 'predicted', average, warn_for)\n",
      "/anaconda3/envs/Python3/lib/python3.6/site-packages/sklearn/metrics/classification.py:1143: UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples.\n",
      "  'precision', 'predicted', average, warn_for)\n",
      "/anaconda3/envs/Python3/lib/python3.6/site-packages/sklearn/metrics/classification.py:1143: UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples.\n",
      "  'precision', 'predicted', average, warn_for)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Fitting 2 folds for each of 6 candidates, totalling 12 fits\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/anaconda3/envs/Python3/lib/python3.6/site-packages/sklearn/metrics/classification.py:1143: UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples.\n",
      "  'precision', 'predicted', average, warn_for)\n",
      "/anaconda3/envs/Python3/lib/python3.6/site-packages/sklearn/metrics/classification.py:1143: UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples.\n",
      "  'precision', 'predicted', average, warn_for)\n",
      "[Parallel(n_jobs=1)]: Done  12 out of  12 | elapsed:    0.2s finished\n"
     ]
    }
   ],
   "source": [
    "# ------ 训练数据 ------\n",
    "from rasa_nlu.training_data import load_data\n",
    "from rasa_nlu.config import RasaNLUModelConfig\n",
    "from rasa_nlu.model import Trainer\n",
    "from rasa_nlu import config\n",
    "\n",
    "trainer = Trainer(config.load(\"config_spacy.yml\"))\n",
    "training_data = load_data('training_data.json')\n",
    "interpreter = trainer.train(training_data)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-11T06:00:05.391486Z",
     "start_time": "2019-02-11T06:00:05.385503Z"
    }
   },
   "outputs": [],
   "source": [
    "# 实体识别\n",
    "import spacy\n",
    "\n",
    "# iexfinance\n",
    "from iexfinance.stocks import Stock\n",
    "from iexfinance.stocks import get_historical_data\n",
    "from iexfinance.stocks import get_historical_intraday\n",
    "\n",
    "# 数据库\n",
    "import sqlite3\n",
    "\n",
    "# json\n",
    "import sys\n",
    "import requests\n",
    "import json\n",
    "\n",
    "# 时间\n",
    "from datetime import datetime\n",
    "import time\n",
    "\n",
    "# 绘图\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "# 正则表达式\n",
    "import re\n",
    "\n",
    "# 随机回复句子\n",
    "import random\n",
    "\n",
    "import string"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ------ 状态 ------\n",
    "\n",
    "CONFUSE = -1\n",
    "INIT = 0\n",
    "MAIN = 1\n",
    "\n",
    "# stock\n",
    "CRT_PRICE = 2\n",
    "HIS_PRICE = 3\n",
    "\n",
    "# weather\n",
    "CITY_ASK = 4\n",
    "GET_WEATHER = 5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ------ 回复语句 ------\n",
    "\n",
    "response_group = {\n",
    "    # ------ 客套 ------\n",
    "    \"greet\":[\"Hi! I am a chatbot. What can I do for you?\",\n",
    "             \"Nice to meet you. I'm a chatbot and I'm ready to help you.\",\n",
    "            ],\n",
    "    \"finish\":[\"OK. Tell me when you need more assists!\",\n",
    "              \"Alright. I'm glad to help you!\",\n",
    "             ],\n",
    "    \"function_intro\":[\"Currently I can help you with: \\n1. Get stock information \\n    1.1 Get current data \\n    1.2 Get historical data \\n    1.3 Analyze certain stocks \\n2. Get weather information(every provience in China, seven days)\"],\n",
    "\n",
    "    \n",
    "    # ------ 否定 ------\n",
    "    \"deny\":[\"Fine, as you wish.\\n\\n{}\",\n",
    "            \"OK, I'll deal with it.\\n\\n{}\",\n",
    "           ],\n",
    "    \n",
    "    \n",
    "    # ------ stock ------\n",
    "    \"current_price\":[\"The current price of {} is {}, and there are some news about {}:\\n{}\",\n",
    "                     \"{} has a real-time price of {}, and there are some news about {}:\\n{}\",\n",
    "                    ], \n",
    "    \"vague_historical_data\":[\"Please specify which time of data you want to query.\",\n",
    "                             \"Which time do you want to know?\"\n",
    "                            ],\n",
    "    \"analyze\":[\"The Earning Per Share (TTM) of {} is currently {}.\"],\n",
    "    \n",
    "    \n",
    "    # ------ weather ------\n",
    "    \"city_ask\":[\"Which city do you want to know?\",\n",
    "                \"Could you please tell the exact city?\",\n",
    "               ],\n",
    "    \"weather_continue\":[\"Here is some weather information:\\n{}\",\n",
    "                        \"I have found some information:\\n{}\",\n",
    "                       ],\n",
    "}\n",
    "\n",
    "def resp_sentence(intent):\n",
    "    return random.choice(response_group[intent])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ------ 状态机 ------\n",
    "\n",
    "policy_rules = {\n",
    "    # ------------ 客套 ------------\n",
    "    (INIT, \"greet\"): (MAIN, resp_sentence(\"greet\"), None),\n",
    "    (MAIN, \"greet\"): (MAIN, resp_sentence(\"greet\"), None),\n",
    "    (MAIN, \"finish\"): (MAIN, resp_sentence(\"finish\"), None),\n",
    "    \n",
    "    # ------------ 功能介绍 ------------\n",
    "    (MAIN,\"function_intro\"): (MAIN, resp_sentence(\"function_intro\"), None),\n",
    "\n",
    "    \n",
    "    \n",
    "    # ------------ stock ------------\n",
    "    \n",
    "    # ------ 当前价格 ------\n",
    "    # 获取当前价格\n",
    "    (MAIN, \"current_price\"): (CRT_PRICE, resp_sentence(\"current_price\"), None),\n",
    "    # 多次获取当前价格\n",
    "    (CRT_PRICE, \"current_price\"): (CRT_PRICE, resp_sentence(\"current_price\"), None),\n",
    "    # 完成，返回主菜单\n",
    "    (CRT_PRICE, \"finish\"): (MAIN, resp_sentence(\"finish\"), None),\n",
    "   \n",
    "    # ------ 历史数据 ------\n",
    "    # 得到清晰的历史数据信息\n",
    "    (MAIN, \"clear_historical_data\"): (MAIN, \"Here is a figure:\", None),\n",
    "    # 得到模糊的历史数据信息，询问详情\n",
    "    (MAIN, \"vague_historical_data\"): (MAIN, resp_sentence(\"vague_historical_data\"), HIS_PRICE),\n",
    "    (HIS_PRICE, \"vague_historical_data\"): (MAIN, resp_sentence(\"vague_historical_data\"), HIS_PRICE),\n",
    "    # 得到附加信息\n",
    "    (MAIN, \"add_historical_data\"): (HIS_PRICE, \"Here is a figure:\", None),\n",
    "    (HIS_PRICE, \"vague_historical_data\"): (HIS_PRICE, \"Here is a figure:\", None),\n",
    "    # 完成，返回主菜单\n",
    "    (HIS_PRICE, \"finish\"): (MAIN, resp_sentence(\"finish\"), None),\n",
    "    \n",
    "    # ------ 建议 ------\n",
    "    (MAIN, \"analyze\"): (MAIN, resp_sentence(\"analyze\"), None),\n",
    "    \n",
    "    \n",
    "    # ------------ weather ------------\n",
    "    (MAIN, \"city_ask\"): (MAIN, resp_sentence(\"city_ask\"), CITY_ASK),\n",
    "    (MAIN, \"weather_continue\"): (CITY_ASK, resp_sentence(\"weather_continue\"), GET_WEATHER),\n",
    "    (MAIN, \"deny\"): (GET_WEATHER, resp_sentence(\"deny\"), None),\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "code_folding": []
   },
   "outputs": [],
   "source": [
    "# ------ 核心功能 ------\n",
    "\n",
    "# 发送消息\n",
    "def send_message(state, pending, message):\n",
    "    # print(\"old_state: \", state, \"message: \", message, \"pending: \", pending)\n",
    "    new_state, response, pending_state = respond(state, message)\n",
    "    \n",
    "    # print(\"new_state: \", new_state, \"response: \", response, \"pending_state: \", pending_state)\n",
    "    \n",
    "    if pending is not None:\n",
    "        new_state, response, pending_state = policy_rules[pending]\n",
    "    if pending_state is not None:\n",
    "        pending = (pending_state, get_intent(message))\n",
    "        \n",
    "    return new_state, pending, response, get_intent(message)\n",
    "\n",
    "\n",
    "\n",
    "weekday = []\n",
    "city = \"\"\n",
    "\n",
    "# 返回状态\n",
    "def respond(state, message):\n",
    "    entity = get_entity(message)\n",
    "\n",
    "    # print(\"res_state: \", state, \"intent: \", get_intent(message))\n",
    "    \n",
    "    # 如果状态错误，报错 \n",
    "    try:\n",
    "        new_state = policy_rules[(state, get_intent(message))][0]\n",
    "        # print(new_state)\n",
    "    except KeyError:\n",
    "        new_state = CONFUSE\n",
    "    pending_state = policy_rules[(state, get_intent(message))][2]\n",
    "    \n",
    "    \n",
    "    # ------ 客套 ------\n",
    "    # 欢迎\n",
    "    if get_intent(message) == 'greet':\n",
    "        response = policy_rules[(state, get_intent(message))][1]\n",
    "    # 结束\n",
    "    if get_intent(message) == 'finish':\n",
    "        response = policy_rules[(state, get_intent(message))][1]\n",
    "    \n",
    "    # ------ 询问功能信息 ------ \n",
    "    if get_intent(message) == 'function_intro':\n",
    "        response = policy_rules[(state, get_intent(message))][1]\n",
    "        \n",
    "    \n",
    "    # ------ 股票 ------\n",
    "    # 询问当前价格\n",
    "    if get_intent(message) == 'current_price':\n",
    "        response = policy_rules[(state, get_intent(message))][1].format(entity, get_current_price(entity), entity, get_news(entity))\n",
    "    # 询问历史价格（信息清楚）\n",
    "    if get_intent(message) == 'clear_historical_data':\n",
    "        response = policy_rules[(state, get_intent(message))][1]\n",
    "        generate_figure(message)\n",
    "    # 询问历史价格（信息模糊）\n",
    "    if get_intent(message) == 'vague_historical_data':\n",
    "        response = policy_rules[(state, get_intent(message))][1]\n",
    "    # 询问历史价格（附加信息）\n",
    "    if get_intent(message) == 'add_historical_data':\n",
    "        response = policy_rules[(state, get_intent(message))][1]\n",
    "        generate_figure(message)\n",
    "    # 分析 及给出TTM\n",
    "    if get_intent(message) == 'analyze':\n",
    "        response = policy_rules[(state, get_intent(message))][1].format(entity,get_ttmEPS(entity))\n",
    "    \n",
    "    \n",
    "    # ------ 天气 ------\n",
    "    # 问用户城市\n",
    "    if get_intent(message) == 'city_ask':\n",
    "        response = policy_rules[(state, get_intent(message))][1]\n",
    "        global weekday \n",
    "        weekday = get_weekday(message)\n",
    "    # 返回天气\n",
    "    if get_intent(message) == 'weather_continue':\n",
    "        response = policy_rules[(state, get_intent(message))][1].format(get_weather(weekday, message))\n",
    "        global city \n",
    "        city = message\n",
    "    # 否定实体\n",
    "    if get_intent(message) == 'deny':\n",
    "        response = policy_rules[(state, get_intent(message))][1].format(get_deny_weather(weekday, city, message))\n",
    "        \n",
    "    return new_state, response, pending_state\n",
    "\n",
    "# 提取意图\n",
    "def get_intent(message):\n",
    "    return interpreter.parse(message)['intent']['name']\n",
    "\n",
    "# 提取实体\n",
    "def get_entity(message):\n",
    "    \n",
    "    # 客套 没有实体\n",
    "    if interpreter.parse(message)['entities'] == []:\n",
    "        return []\n",
    "    \n",
    "    # 询问当前价格 / 历史价格 / 分析 如果实体是公司，提取公司名\n",
    "    if interpreter.parse(message)['entities'][0]['entity'] == 'company':\n",
    "        return interpreter.parse(message)['entities'][0]['value']\n",
    "  \n",
    "    # 给附加信息 提取开始和结束时间\n",
    "        return [interpreter.parse(message)['entities'][0]['value'],\n",
    "                interpreter.parse(message)['entities'][1]['value']]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ------ 股票信息 ------\n",
    "\n",
    "# 获取某股票的当前价格\n",
    "def get_current_price(company):\n",
    "    print(\"Company: \", company)\n",
    "    \n",
    "    prices = Stock(company).get_price()\n",
    "    return prices\n",
    "\n",
    "# 获取某股票的每股利润\n",
    "def get_ttmEPS(company):\n",
    "    ttmEPS = Stock(company).get_key_stats()['ttmEPS']\n",
    "    return ttmEPS\n",
    "\n",
    "# 获取某股票相关新闻\n",
    "def get_news(company):\n",
    "    news = Stock(company).get_news()\n",
    "    for i in news:\n",
    "        if i['summary'] != 'No summary available.':\n",
    "            return i['url']\n",
    "    \n",
    "# 生成历史数据折线图\n",
    "def generate_figure(message):\n",
    "    comprehended_data = interpreter.parse(message)\n",
    "  \n",
    "    for i in range(0,2):\n",
    "        # 获取公司名称\n",
    "        if comprehended_data['entities'][i]['entity'] == 'company':\n",
    "            required_company = comprehended_data['entities'][i]['value']\n",
    "        \n",
    "        # 获取数据类型 open / close / high\n",
    "        if comprehended_data['entities'][i]['entity'] == 'his_price_type':\n",
    "            required_type = comprehended_data['entities'][i]['value']\n",
    "        \n",
    "        # 默认值\n",
    "        else:\n",
    "            required_company = 'AAPL'\n",
    "            required_type = 'close'\n",
    "            \n",
    "    # 对模糊的历史数据询问的补充信息\n",
    "    if len(comprehended_data['entities']) <= 3:\n",
    "        \n",
    "        # 时间格式：2019-1-1\n",
    "        time_period = [comprehended_data['entities'][0]['value'],\n",
    "                       comprehended_data['entities'][1]['value']]\n",
    "\n",
    "        start_time_splited = time_period[0].split(' - ')\n",
    "        end_time_splited = time_period[1].split(' - ')\n",
    "        \n",
    "        # 开始时间\n",
    "        # print(start_time_splited)\n",
    "        \n",
    "        start_year = int(start_time_splited[0])\n",
    "        start_month = int(start_time_splited[1])\n",
    "        start_day = int(start_time_splited[2])\n",
    "        \n",
    "        # print(\"Start year: \", start_year, \", Start month: \", start_month, \", Start day\", start_day)\n",
    "        \n",
    "        # 结束时间\n",
    "        end_year = int(end_time_splited[0])\n",
    "        end_month = int(end_time_splited[1])\n",
    "        end_day = int(end_time_splited[2])\n",
    "\n",
    "        start_time = datetime(start_year, start_month, start_day)\n",
    "        end_time = datetime(end_year, end_month, end_day)\n",
    "        \n",
    "        # 生成该时间段的线形图\n",
    "        his_data = get_historical_data(required_company,start_time,end_time,output_format='pandas')\n",
    "\n",
    "    # 完整的历史数据询问\n",
    "    else:\n",
    "        # 时间格式：2019-1-1\n",
    "        time_period = [comprehended_data['entities'][2]['value'],\n",
    "                       comprehended_data['entities'][3]['value']]\n",
    "\n",
    "        start_time_splited = time_period[0].split('-')\n",
    "        end_time_splited = time_period[1].split('-')\n",
    "\n",
    "        # print(start_time_splited)\n",
    "        \n",
    "        # 开始时间\n",
    "        start_year = int(start_time_splited[0])\n",
    "        start_month = int(start_time_splited[1])\n",
    "        start_day = int(start_time_splited[2])\n",
    "    \n",
    "        # 结束时间\n",
    "        end_year = int(end_time_splited[0])\n",
    "        end_month = int(end_time_splited[1])\n",
    "        end_day = int(end_time_splited[2])\n",
    "\n",
    "        start_time = datetime(start_year, start_month, start_day)\n",
    "        end_time = datetime(end_year, end_month, end_day)\n",
    "        \n",
    "        # 生成该时间段的线形图\n",
    "        his_data = get_historical_data(required_company,start_time,end_time,output_format='pandas')\n",
    "    \n",
    "    # 画图\n",
    "    plot_required_type = his_data[required_type].plot()\n",
    "    fig = plot_required_type.get_figure()\n",
    "    fig.savefig('result.png')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ------ 天气信息 ------\n",
    "\n",
    "\n",
    "# ------ 获得星期数 ------\n",
    "week = {'Monday':1, 'Tuesday':2, 'Wednesday':3, 'Thursday':4, 'Friday':5, 'Saturday':6, 'Sunday':0}\n",
    "\n",
    "def get_weekday(message):\n",
    "    # 匹配询问的星期\n",
    "    weekday = re.findall(\"[A-Z]+[a-z]*\",message)\n",
    "\n",
    "    # 没有星期，默认为今天\n",
    "    if weekday == []:\n",
    "        return [0]\n",
    "    \n",
    "    else:\n",
    "        # 今天的星期\n",
    "        today = int(time.strftime(\"%w\"))\n",
    "\n",
    "        # api中要查找的列数\n",
    "        number = []\n",
    "        \n",
    "        for day in weekday:\n",
    "            n = week[day] - today\n",
    "            if(n < 0):\n",
    "                n = n + 7            \n",
    "            number.append(n)\n",
    "            \n",
    "        return number\n",
    "\n",
    "\n",
    "    \n",
    "# ------ 在数据库中查省份代号（用于天气api） ------\n",
    "\n",
    "def get_citycode(city):\n",
    "    conn = sqlite3.connect('city_code.db')\n",
    "    c = conn.cursor()\n",
    "    \n",
    "    code = ''\n",
    "    \n",
    "    query = \"SELECT * FROM city WHERE name = '\" + city + \"'\"\n",
    "    c.execute(query)\n",
    "    result =  c.fetchall()\n",
    "    \n",
    "    for row in result:\n",
    "       code = row[0]\n",
    "    \n",
    "    return code\n",
    "\n",
    "\n",
    "\n",
    "# ------ 调用api返回各省天气信息 ------\n",
    "def get_weather(day_list, city):\n",
    "\n",
    "    # 申请一个key：https://www.juhe.cn/docs/api/id/39\n",
    "    weather_key = \"\"\n",
    "    \n",
    "    # 省份编号\n",
    "    code = get_citycode(city)\n",
    "    \n",
    "    url = \"http://v.juhe.cn/weather/index?format=2&cityname=\" + code + \"&key=\" + weather_key       \n",
    "    req = requests.get(url)    \n",
    "    info = dict(req.json())\n",
    "    info = info['result']['future']\n",
    "    # print(info)\n",
    "    \n",
    "    \n",
    "    response = \"\"\n",
    "    \n",
    "    for number in day_list:\n",
    "        newinfo = info[number]\n",
    "        temperature = newinfo['temperature']\n",
    "        weather = newinfo['weather']\n",
    "        wind = newinfo['wind']\n",
    "        week = newinfo['week']\n",
    "        date = newinfo['date']\n",
    "        response = response + \"日期: \" + date + \" \" + week + \", 温度: \" + temperature + \", 天气: \" + weather + \", 风向与风力: \" + wind + \"\\n\"\n",
    "        \n",
    "    return response\n",
    "\n",
    "\n",
    "def get_deny_weather(day_list, city, message):\n",
    "    # print(\"old: \", day_list)\n",
    "    \n",
    "    # 匹配询问的星期\n",
    "    weekday = re.findall(\"[A-Z]+[a-z]*\",message)\n",
    "       \n",
    "    # 今天的星期\n",
    "    today = int(time.strftime(\"%w\"))\n",
    "    \n",
    "    # 移除否定的星期\n",
    "    for day in weekday:\n",
    "        n = week[day] - today\n",
    "        if(n < 0):\n",
    "            n = n + 7            \n",
    "        day_list.remove(n)\n",
    "    \n",
    "    # print(\"new: \", day_list)\n",
    "    \n",
    "    return get_weather(day_list, city)\n",
    "    \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-11T05:59:30.030033Z",
     "start_time": "2019-02-11T05:59:21.447980Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "█\r"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Getting uuid of QR code.\n",
      "Downloading QR code.\n",
      "Please scan the QR code to log in.\n",
      "Please press confirm on your phone.\n",
      "Loading the contact, this may take a little while.\n",
      "Login successfully as 二十四桥明月夜\n",
      "Start auto replying.\n"
     ]
    }
   ],
   "source": [
    "'''\n",
    "# ------ 终端调试 ------\n",
    "\n",
    "while True:\n",
    "    state = MAIN\n",
    "    pending = None\n",
    "\n",
    "    msg = input()\n",
    "    print(\"USER: \" + msg)\n",
    "    print(\"[Intent: \" + get_intent(msg) + \"]\")\n",
    "\n",
    "    state, pending, final_response, message_intent = send_message(state, pending, msg)\n",
    "\n",
    "    print(\"BOT: \" + final_response)\n",
    "'''    \n",
    "\n",
    "\n",
    "\n",
    "# ------ 部署到微信 ------\n",
    "\n",
    "# wxpy\n",
    "\n",
    "from wxpy import *\n",
    "\n",
    "# 创建bot\n",
    "bot = Bot()\n",
    "\n",
    "# 对话对象\n",
    "my_friend = bot.friends().search('恶龙')[0]\n",
    "\n",
    "\n",
    "@bot.register(my_friend, TEXT)\n",
    "def auto_reply(msg):\n",
    "    state = MAIN\n",
    "    pending = None\n",
    "    print(get_intent(msg.text))\n",
    "    \n",
    "    state, pending, final_response, message_intent = send_message(state, pending, msg.text)\n",
    "    msg.reply(final_response)\n",
    "    # 发送图片\n",
    "    if message_intent == 'clear_historical_data' or message_intent == 'add_historical_data':\n",
    "        msg.reply_image('result.png')\n",
    "    return fianl_response\n",
    "\n",
    "# 注册机器人\n",
    "bot.registered\n",
    "\n",
    "\n",
    "'''\n",
    "# itchat\n",
    "import itchat\n",
    "from itchat.content import *\n",
    "\n",
    "# 登录\n",
    "itchat.auto_login()\n",
    "\n",
    "\n",
    "# 对话对象\n",
    "my_friend = itchat.search_friends(name=\"恶龙\")[0]['UserName']\n",
    "\n",
    "@itchat.msg_register([TEXT, PICTURE])\n",
    "def auto_reply(msg):\n",
    "    state = MAIN\n",
    "    pending = None\n",
    "  \n",
    "    state, pending, final_response, message_intent = send_message(state, pending, msg['Text'])\n",
    "    itchat.send(final_response, toUserName = my_friend)\n",
    "    \n",
    "    # 发送图片\n",
    "    if message_intent == 'clear_historical_data' or message_intent == 'add_historical_data':\n",
    "        itchat.send_image('result.png',  toUserName = my_friend)\n",
    "    # return final_response\n",
    "\n",
    "# 启动机器人\n",
    "itchat.run()\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "        "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python3",
   "language": "python",
   "name": "py3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7"
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autoclose": false,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
